package com.christina.engine.parameter.builder;

import com.christina.engine.context.model.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户偏好建造者
 * 负责构建和验证用户偏好设置
 * 
 * @author Christina
 */
@Slf4j
@Component
public class UserPreferencesBuilder extends ParameterBuilder<UserContext.UserPreferences> {
    
    private static final List<String> VALID_LANGUAGES = Arrays.asList(
            "zh-CN", "en-US", "ja-JP", "ko-KR", "fr-FR", "de-DE", "es-ES"
    );
    
    private static final List<String> VALID_THEMES = Arrays.asList(
            "light", "dark", "auto"
    );
    
    private static final List<String> VALID_NOTIFICATION_TYPES = Arrays.asList(
            "all", "important", "none"
    );
    
    public UserPreferencesBuilder() {
        // 设置默认值
        setDefault("language", "zh-CN");
        setDefault("theme", "light");
        setDefault("timezone", "Asia/Shanghai");
        setDefault("notificationLevel", "important");
        setDefault("soundEnabled", true);
        setDefault("aiSuggestionsEnabled", true);
        setDefault("privacyLevel", "standard");
        setDefault("dataRetentionDays", 90);
        setDefault("autoSave", true);
        setDefault("customPreferences", new HashMap<String, Object>());
        
        // 添加验证规则
        addValidation("language", 
                value -> value == null || VALID_LANGUAGES.contains(value.toString()),
                "不支持的语言设置");
        
        addValidation("theme",
                value -> value == null || VALID_THEMES.contains(value.toString()),
                "无效的主题设置");
        
        addValidation("notificationLevel",
                value -> value == null || VALID_NOTIFICATION_TYPES.contains(value.toString()),
                "无效的通知级别");
        
        addValidation("dataRetentionDays",
                value -> {
                    if (value == null) return true;
                    try {
                        int days = Integer.parseInt(value.toString());
                        return days >= 1 && days <= 365;
                    } catch (NumberFormatException e) {
                        return false;
                    }
                },
                "数据保留期限必须在1-365天之间");
        
        addValidation("privacyLevel",
                value -> value == null || Arrays.asList("low", "standard", "high", "strict").contains(value.toString()),
                "无效的隐私级别");
    }
    
    /**
     * 设置语言偏好
     * 
     * @param language 语言代码
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder language(String language) {
        return (UserPreferencesBuilder) addParameter("language", language);
    }
    
    /**
     * 设置主题偏好
     * 
     * @param theme 主题名称
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder theme(String theme) {
        return (UserPreferencesBuilder) addParameter("theme", theme);
    }
    
    /**
     * 设置时区
     * 
     * @param timezone 时区
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder timezone(String timezone) {
        return (UserPreferencesBuilder) addParameter("timezone", timezone);
    }
    
    /**
     * 设置通知偏好
     * 
     * @param notificationLevel 通知级别
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder notificationLevel(String notificationLevel) {
        return (UserPreferencesBuilder) addParameter("notificationLevel", notificationLevel);
    }
    
    /**
     * 设置是否启用声音
     * 
     * @param soundEnabled 是否启用声音
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder soundEnabled(Boolean soundEnabled) {
        return (UserPreferencesBuilder) addParameter("soundEnabled", soundEnabled);
    }
    
    /**
     * 设置偏好的交通方式
     * 
     * @param transportMode 交通方式
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder preferredTransportMode(String transportMode) {
        return (UserPreferencesBuilder) addParameter("preferredTransportMode", transportMode);
    }
    
    /**
     * 设置偏好的舱位等级
     * 
     * @param seatClass 舱位等级
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder preferredSeatClass(String seatClass) {
        return (UserPreferencesBuilder) addParameter("preferredSeatClass", seatClass);
    }
    
    /**
     * 设置预算范围偏好
     * 
     * @param budgetRange 预算范围
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder budgetRange(String budgetRange) {
        return (UserPreferencesBuilder) addParameter("budgetRange", budgetRange);
    }
    
    /**
     * 设置聊天响应风格
     * 
     * @param chatStyle 聊天风格
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder chatStyle(String chatStyle) {
        return (UserPreferencesBuilder) addParameter("chatStyle", chatStyle);
    }
    
    /**
     * 设置响应长度偏好
     * 
     * @param responseLength 响应长度
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder responseLength(String responseLength) {
        return (UserPreferencesBuilder) addParameter("responseLength", responseLength);
    }
    
    /**
     * 设置是否启用AI建议
     * 
     * @param aiSuggestionsEnabled 是否启用AI建议
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder aiSuggestionsEnabled(Boolean aiSuggestionsEnabled) {
        return (UserPreferencesBuilder) addParameter("aiSuggestionsEnabled", aiSuggestionsEnabled);
    }
    
    /**
     * 设置隐私级别
     * 
     * @param privacyLevel 隐私级别
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder privacyLevel(String privacyLevel) {
        return (UserPreferencesBuilder) addParameter("privacyLevel", privacyLevel);
    }
    
    /**
     * 设置数据保留期限
     * 
     * @param dataRetentionDays 数据保留天数
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder dataRetentionDays(Integer dataRetentionDays) {
        return (UserPreferencesBuilder) addParameter("dataRetentionDays", dataRetentionDays);
    }
    
    /**
     * 设置自动保存偏好
     * 
     * @param autoSave 是否自动保存
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder autoSave(Boolean autoSave) {
        return (UserPreferencesBuilder) addParameter("autoSave", autoSave);
    }
    
    /**
     * 设置快捷键偏好
     * 
     * @param shortcuts 快捷键映射
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder shortcuts(Map<String, String> shortcuts) {
        return (UserPreferencesBuilder) addParameter("shortcuts", shortcuts);
    }
    
    /**
     * 添加自定义偏好
     * 
     * @param key 偏好键
     * @param value 偏好值
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder customPreference(String key, Object value) throws ParameterValidationException {
        @SuppressWarnings("unchecked")
        Map<String, Object> customPrefs = getParameter("customPreferences", Map.class);
        if (customPrefs == null) {
            customPrefs = new HashMap<>();
            addParameter("customPreferences", customPrefs);
        }
        customPrefs.put(key, value);
        return this;
    }
    
    /**
     * 批量设置自定义偏好
     * 
     * @param customPreferences 自定义偏好映射
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder customPreferences(Map<String, Object> customPreferences) throws ParameterValidationException {
        if (customPreferences != null) {
            for (Map.Entry<String, Object> entry : customPreferences.entrySet()) {
                customPreference(entry.getKey(), entry.getValue());
            }
        }
        return this;
    }
    
    /**
     * 从现有偏好对象复制设置
     * 
     * @param existingPreferences 现有偏好对象
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder fromExisting(UserContext.UserPreferences existingPreferences) throws ParameterValidationException {
        if (existingPreferences != null) {
            if (existingPreferences.getLanguage() != null) {
                language(existingPreferences.getLanguage());
            }
            if (existingPreferences.getTheme() != null) {
                theme(existingPreferences.getTheme());
            }
            if (existingPreferences.getTimezone() != null) {
                timezone(existingPreferences.getTimezone());
            }
            if (existingPreferences.getCustomPreferences() != null) {
                customPreferences(existingPreferences.getCustomPreferences());
            }
        }
        return this;
    }
    
    /**
     * 应用默认的出行偏好
     * 
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder applyTravelDefaults() {
        preferredTransportMode("不限");
        preferredSeatClass("经济舱");
        budgetRange("中等");
        return this;
    }
    
    /**
     * 应用默认的聊天偏好
     * 
     * @return 当前建造者实例
     */
    public UserPreferencesBuilder applyChatDefaults() {
        chatStyle("friendly");
        responseLength("medium");
        aiSuggestionsEnabled(true);
        return this;
    }
    
    @Override
    protected void performCustomValidation() throws ParameterValidationException {
        // 验证自定义偏好数量限制
        @SuppressWarnings("unchecked")
        Map<String, Object> customPrefs = getParameter("customPreferences", Map.class);
        if (customPrefs != null && customPrefs.size() > 50) {
            throw new ParameterValidationException("自定义偏好数量不能超过50个");
        }
    }
    
    @Override
    protected UserContext.UserPreferences doBuild() throws ParameterValidationException {
        @SuppressWarnings("unchecked")
        Map<String, Object> customPrefs = getParameter("customPreferences", Map.class);
        @SuppressWarnings("unchecked")
        Map<String, String> shortcuts = getParameter("shortcuts", Map.class);
        
        UserContext.UserPreferences preferences = UserContext.UserPreferences.builder()
                .language(getParameter("language", String.class))
                .theme(getParameter("theme", String.class))
                .timezone(getParameter("timezone", String.class))
                .notificationLevel(getParameter("notificationLevel", String.class))
                .soundEnabled(getParameter("soundEnabled", Boolean.class))
                .preferredTransportMode(getParameter("preferredTransportMode", String.class))
                .preferredSeatClass(getParameter("preferredSeatClass", String.class))
                .budgetRange(getParameter("budgetRange", String.class))
                .chatStyle(getParameter("chatStyle", String.class))
                .responseLength(getParameter("responseLength", String.class))
                .aiSuggestionsEnabled(getParameter("aiSuggestionsEnabled", Boolean.class))
                .privacyLevel(getParameter("privacyLevel", String.class))
                .dataRetentionDays(getParameter("dataRetentionDays", Integer.class))
                .autoSave(getParameter("autoSave", Boolean.class))
                .shortcuts(shortcuts)
                .customPreferences(customPrefs)
                .build();
        
        log.debug("Built UserPreferences: language={}, theme={}, customPrefs={}", 
                preferences.getLanguage(), preferences.getTheme(), 
                customPrefs != null ? customPrefs.size() : 0);
        
        return preferences;
    }
    
    /**
     * 创建新的建造者实例
     * 
     * @return 新的建造者实例
     */
    public static UserPreferencesBuilder newBuilder() {
        return new UserPreferencesBuilder();
    }
}